#!/usr/bin/env node

const { Client } = require('pg');
const fs = require('fs').promises;
const path = require('path');

// PostgreSQL connection configuration
const pgConfig = {
  host: 'localhost',
  port: 15432,
  user: 'postgres',
  password: 'qwe!@#',
  database: 'Eng'
};

/**
 * Extract pronunciation data for words from txt files
 */
async function extractPronunciations() {
  console.log('Starting extraction of pronunciations...');
  
  // Connect to PostgreSQL
  const pgClient = new Client(pgConfig);
  
  try {
    await pgClient.connect();
    console.log('Connected to PostgreSQL database');
    
    // Process all subdirectories in resources/dic
    const dicPath = path.join(__dirname, '../resources/dic');
    const letters = await fs.readdir(dicPath);
    
    // Filter only directories (a-z)
    const letterDirs = letters.filter(item => /^[a-z]$/.test(item));
    
    console.log(`Found ${letterDirs.length} letter directories to process`);
    
    for (const letter of letterDirs) {
      const letterPath = path.join(dicPath, letter);
      console.log(`Processing directory: ${letter}`);
      
      try {
        const files = await fs.readdir(letterPath);
        const txtFiles = files.filter(file => path.extname(file) === '.txt');
        
        if (txtFiles.length === 0) {
          console.log(`No txt files found in ${letterPath}`);
          continue;
        }
        
        console.log(`Found ${txtFiles.length} txt files in ${letterPath}`);
        
        for (const txtFile of txtFiles) {
          const word = path.basename(txtFile, '.txt');
          const outputPath = path.join(letterPath, `${word}-pron.txt`);
          
          // Check if output file already exists
          try {
            await fs.access(outputPath);
            console.log(`Output file already exists for ${word}, skipping...`);
            continue;
          } catch (err) {
            // File doesn't exist, continue processing
          }
          
          try {
            // Query pronunciation from database
            const query = 'SELECT pronounce FROM public.enwords WHERE word = $1';
            const res = await pgClient.query(query, [word]);
            
            if (res.rows.length > 0 && res.rows[0].pronounce) {
              const pronunciation = res.rows[0].pronounce;
              
              // Write pronunciation to file
              await fs.writeFile(outputPath, pronunciation, 'utf8');
              console.log(`Written pronunciation for "${word}" to ${outputPath}`);
            } else {
              console.log(`No pronunciation found for word: "${word}"`);
              // Create empty file to indicate processing was attempted
              // await fs.writeFile(outputPath, '', 'utf8');
            }
          } catch (err) {
            console.error(`Error processing word "${word}":`, err.message);
          }
        }
      } catch (err) {
        console.error(`Error processing directory ${letterPath}:`, err.message);
      }
    }
    
    console.log('Finished processing all directories');
  } catch (err) {
    console.error('Database connection error:', err.message);
  } finally {
    await pgClient.end();
    console.log('Disconnected from PostgreSQL database');
  }
}

// Run the function
if (require.main === module) {
  extractPronunciations().catch(err => {
    console.error('Error in main execution:', err);
    process.exit(1);
  });
}

module.exports = extractPronunciations;